// pages/defect/adjustment/index.js
import {
  _list,
  _add,
  _update,
  _remove
} from '../../../api/workmanship-param-glazing'
import {
  _add as paramTypeAdd,
  _list as paramTypeList
} from '../../../api/workmanship-param-type';
import {
  PARAMS_TYPE
} from '../../../dataSource'
let ids = [];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataSource: [],
    _parent: {},
    disabledSwipe: false,
    addParamsShow: false,
    PARAMS_TYPE
  },
  toCraft(event) {
    const {
      data,
      item
    } = event.currentTarget.dataset;
    const ancestor = encodeURIComponent(JSON.stringify(this.data._parent)),
      father = encodeURIComponent(JSON.stringify(item)),
      grandfather = encodeURIComponent(JSON.stringify(data));

    wx.navigateTo({
      url: '../tables/index?' + `ancestor=${ancestor}&father=${father}&grandfather=${grandfather}`,
    })
  },
  onSwipeDisabld(event) {
    // const len = event.currentTarget.dataset.length;
    // if (Number.parseInt(len) < 4) {
    //   return
    // }
    // this.setData({
    //   disabledSwipe: true
    // })
  },
  onSwipeEnable(event) {
    // const len = event.currentTarget.dataset.length;
 
    // if (Number.parseInt(len) < 4) {
    //   return
    // }
    // this.setData({
    //   disabledSwipe: false
    // })
  },
  onEdit(event) {
    const {
      index,
      item
    } = event.currentTarget.dataset;
    const dataSource = this.data.dataSource;
    wx.showModal({
      editable: true,
      title: '输入名称',
      placeholderText: '输入',
      content: item.name,
      success: res => {
        if (res.confirm) {
          if (res.content) {
            _update({
              ...item,
              name: res.content
            }, () => {
              dataSource[index] = {
                ...item,
                name: res.content
              }
              this.setData({
                dataSource
              })
            })
          } else {
            wx.showToast({
              title: '名称无效',
              icon: 'none'
            })
          }
        }
      }
    })
  },
  onAdd() {
    wx.showModal({
      editable: true,
      title: '输入名称',
      placeholderText: '输入',
      success: res => {
        if (res.confirm) {
          if (res.content) {
            _add({
              name: res.content,
              adjustmentGlazeTypeId: this.data._parent['id']
            }, this.fetchData)
          } else {
            wx.showToast({
              title: '名称无效',
              icon: 'none'
            })
          }
        }
      }
    })
  },
  onBack() {
    wx.navigateBack()
  },
  onDelect(event) {
    const dataSource = this.data.dataSource,
      index = event.currentTarget.dataset.index;
    wx.showModal({
      title: '确定要删除吗？',
      icon: 'none',
      success: res => {
        if (res.confirm) {
          _remove(dataSource[index], () => {
            dataSource.splice(index, 1);
            this.setData({
              dataSource
            })
          })
        }
      }
    })
  },
  fetchData() {
    _list({
      adjustmentGlazeTypeId: this.data._parent['id']
    }, res => {
      this.setData({
        dataSource: res
      })
      this.setWorkmanshipParamGlazingIds(res)
    })
  },
  setWorkmanshipParamGlazingIds(data) {
    ids = data.map(it => it.id);
    this.fetchParamTypeList(ids.join(','));
  },
  onUpdateParams() {
    this.setWorkmanshipParamGlazingIds(this.data.dataSource)
  },
  onAddParamsCancel() {
    this.setData({
      addParamsShow: false
    })
  },
  onAddParamsShow(event) {
    const item = event.currentTarget.dataset.item;
    const params = PARAMS_TYPE.filter(it => {
      return item['_params'].find(k => {
        return k['paramType'] === it['value']
      }) === undefined
    });
    if (params.length < 1) {
      wx.showToast({
        title: '已添加所有可选参数',
        icon: 'none'
      })
      return
    }
    const instance = this.selectComponent('#params');
    instance?.initData(item);

    instance?.setParamsType(params);
    this.setData({
      addParamsShow: true
    })
  },
  onAddParamsSubmit(event) {
    paramTypeAdd(event.detail, () => {
      this.fetchParamTypeList(ids.join(','));
    })
    this.onAddParamsCancel();
  },
  fetchParamTypeList(ids) {
    paramTypeList({
      workmanshipParamGlazingIds: ids
    }, res => {
      const dataSource = this.data.dataSource.map(it => {
        return {
          ...it,
          _params: res.filter(item => item.workmanshipParamGlazingId === it.id).map(it => {
            return {
              ...it,
              _name: PARAMS_TYPE.find(item => item.value === it.paramType)?.['name'] ?? '未知'
            }
          })
        }
      })
      this.setData({
        dataSource
      })
    })
  },
  onParamEdit(event) {
    const {
      item,
      data
    } = event.currentTarget.dataset;
    const _optionsInstance = this.selectComponent("#_options");
    _optionsInstance?.open(item, data)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    try {
      this.setData({
        _parent: JSON.parse(decodeURIComponent(options.data))
      })
      this.fetchData();
    } catch (e) {
      wx.navigateBack()
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})